// 设备拓扑
<template>
  <div>
    <el-dialog
      v-el-drag-dialog="{resize: resize, updataFull, updataDialogWidth}"
      :fullscreen="isfullscreen"
      :title="dialogTitle"
      :visible="dialogVisible"
      custom-class="device-topo-dialog"
      :width="setDialogWidth('1200px')"
      :append-to-body="true"
      @close="close"
    >
      <div id="topoNodeBox" class="topo-node-box">
        <vis-view
          id="deviceTopo"
          ref="deviceTopo"
          topo-type="device"
          :nodes="nodes"
          :edges="edges"
          :is-edit="isEdit"
          :show-eagel-eye="false"
          @selectNode="selectNode"
          @hoverNode="hoverNode"
          @hoverEdge="hoverEdge"
          @selectEdge="selectEdge"
          @disableEdit="isEdit = false"
        />
        <div class="topo-node-btn">
          <el-button type="primary" @click="getData">{{ $t('REFRESH') }}</el-button>
          <el-button v-if="!isEdit" type="primary" @click="isEdit = true">{{
            $t('EDIT')
          }}</el-button>
          <el-button v-else type="primary" @click="saveTopos">{{ $t('SAVE') }}</el-button>
        </div>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="close">{{ $t('CLOSE') }}</el-button>
      </span>
    </el-dialog>
    <!-- <splice-closure-detail
      v-show="spliceClosureHover"
      :style="hoverPosition"
      style="z-index: 2999"
      :params="curNodeData"
      class="absolute"
    /> -->
    <segment-detail
      v-if="segmentShow"
      ref="editBox"
      :set-edit="setEdit"
      :visible="segmentShow"
      type="view"
      :row-data="rowData"
      @close="closeSegment"
    />
    <div
      v-if="activeEdge.channelName"
      class="absolute el-tabs--card"
      :style="hoverPosition"
      style="z-index: 2999"
    >
      <div class="flex flex-wrap justify-between el-tab-pane">
        <div class="w-100">
          <div class="title pb-10">{{ activeEdge.channelName + '-' + $t('CHANNEL_NUMBER') }}</div>
        </div>
        <p class="w-50">
          <span class="item-name">{{ $t('IDLE') }}：</span>
          <span class="item-value">{{ activeEdge.subInfo.idle }}</span>
        </p>
        <p class="w-50">
          <span class="item-name">{{ $t('MAIN') }}：</span>
          <span class="item-value">{{ activeEdge.subInfo.main }}</span>
        </p>
        <p class="w-50">
          <span class="item-name">{{ $t('STANDBY') }}：</span>
          <span class="item-value">{{ activeEdge.subInfo.backup || 0 }}</span>
        </p>
        <p class="w-50">
          <span class="item-name">{{ $t('DAMAGE') }}：</span>
          <span
            class="item-value"
            style="color: #cc3333;"
          >
            {{ activeEdge.subInfo.damage }}
          </span>
        </p>
        <p class="w-50">
          <span class="item-name">{{ $t('TOTAL_COUNT') }}：</span>
          <span class="item-value">{{ activeEdge.subInfo.sum || 0 }}</span>
        </p>
      </div>
    </div>
  </div>
</template>
<script>
  import { get } from 'lodash'
  import topoPositionApi from '@/api/oen/TopoPositionApi'
  import routeSegmentApi from '@/api/oen/RouteSegmentApi'
  import nodeApi from '@/api/oen/NodeApi'
  import { changeDecimal } from '@/utils/common'
  import { formatEdges, formatNodes } from '@/views/module/home/components/vis/js/format'
  // import VisView from '@/views/module/home/components/vis'
  import VisView from '@/views/module/home/components/antv-g6/device'
  import SegmentDetail from '@/views/module/conf/segment/Edit'
  // import SpliceClosureDetail from './SpliceClosureDetail'

  export default {
    components: {
      VisView,
      SegmentDetail
      // SpliceClosureDetail
    },
    props: {
      dialogVisible: {
        type: Boolean,
        default: false
      },
      node: {
        type: Object,
        default: () => {}
      },
      operateType: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        stationData: {},
        nodesData: [],
        edges: [],
        nodes: [],
        deviceList: [],
        rowData: {},
        segmentShow: false,
        setEdit: true,
        isEdit: false,
        spliceClosureHover: false,
        curNodeData: {},
        activeEdge: { subInfo: {}},
        hoverPosition: {
          left: 0,
          right: 0,
          bottom: 0
        }
      }
    },
    computed: {
      dialogTitle() {
        return `${this.$store.getters.dictMap.REGION_TYPE[this.stationData.type]}-${this.stationData.label}`
      }
    },
    watch: {
      segmentShow(newVal) {
        if (!newVal) return
        this.$nextTick(() => {
          console.log(this.$refs.editBox)
          this.$refs.editBox && this.$refs.editBox.open()
        })
      },
      isEdit(newVal) {
        this.$refs.deviceTopo.setEditable(newVal)
      }
    },
    mounted() {
      // console.log(this.node)
      this.stationData = { ...this.node }
      this.getData()
    },
    methods: {
      // 弹窗关闭
      closeSegment() {
        this.setEdit = false
        this.$nextTick(() => {
          this.setEdit = true
        })
        this.segmentShow = false
      },
      resize() {
        document.getElementById('topoNodeBox').style.height =
          document.getElementById('topoNodeBox').parentNode.offsetHeight - 50 + 'px'
        // this.$refs.deviceTopo && this.$refs.deviceTopo.init()
        const topoNodeBoxWH = document.getElementById('topoNodeBox').getBoundingClientRect()
        this.$refs.deviceTopo && this.$refs.deviceTopo.fitView(topoNodeBoxWH.width, topoNodeBoxWH.height)
      },
      getData() {
        this.nodes = []
        this.edges = []
        this.deviceList = []
        this.isEdit = false
        this.$emit('selectDevice', { mouseStatus: 'LEAVE' })
        Promise.all([
          topoPositionApi.getDeviceTopoNodesByRegionId({ regionId: this.stationData.nodeId }),
          nodeApi.queryList({ stationIdList: [this.stationData.nodeId] })
        ]).then(([res1, res2 = []]) => {
          if (res1 && res1.nodes) {
            this.formatData(res1.nodes, res1.edges, res2)
          }
          this.deviceList = res2
        })
      },
      formatData(nodes, edges, deviceList) {
        // 使用网段id作为线条id
        const newEdges = edges.map(i => {
          // const label = `${i.label}
          //       ${this.$t('CHANNEL_NUMBER')}:${this.$t('IDLE')}:${i.subInfo.idle}/${this.$t(
          //   'MAIN'
          // )}:${i.subInfo.main}/${this.$t('DAMAGE')}:${i.subInfo.damage}/${this.$t('TOTAL_COUNT')}:${
          //   i.subInfo.sum
          // }`
          return {
            ...i,
            channelName: i.label,
            id: i.segmentId || null
          }
        })
        const newNodes = nodes.map(i => {
          const nodeData = deviceList.find(j => i.nodeId === j.nodeId) || {}
          // console.log('nodeData', nodeData)
          nodeData.id = i.id
          return {
            ...i,
            ...nodeData
          }
        })
        this.handleNodes(newNodes, newEdges)
      },
      // 保存位置
      saveTopos() {
        // const topoPositions = this.$refs.deviceTopo.myNetwork.getPositions() || {}
        const topoPositions = this.$refs.deviceTopo.graph.save().nodes
        // const nodeList = this.nodes.map(i => {
        //   const position = topoPositions[i.id] || i
        //   const x = position.x
        //   const y = position.y
        //   return {
        //     type: 'NODE',
        //     nodeId: i.nodeId,
        //     x: x,
        //     y: y
        //   }
        // })
        const nodeList = topoPositions.map(i => {
          return {
            type: 'NODE',
            nodeId: i.info.nodeId,
            x: changeDecimal(i.x),
            y: changeDecimal(i.y)
          }
        })
        topoPositionApi
          .savePosition(nodeList)
          .then(res => {
            this.isEdit = false
            this.$message.success(this.$t(res ? 'SAVE_SUCCESS' : 'SAVEFAILED'))
            this.getData()
          })
      },
      handleNodes(nodes, edges) {
        if (nodes) {
          this.nodes = formatNodes(nodes, 'device', this.operateType === 'open')
          console.log('handleNodes', this.nodes)
        }
        if (edges) {
          this.edges = formatEdges(edges)
        }
      },
      selectEdge(obj) {
        if (obj.mouseStatus === 'SELECT') {
          // 查询对应的网段
          routeSegmentApi.getBySegmentId({ segmentId: obj.id }).then(res => {
            if (!res) return
            this.rowData = res
            this.segmentShow = true
          }).catch(err => {
            console.log(err)
          })
        }
      },
      selectNode(obj) {
        console.log('当前设备', obj)
        // 根据节点id去原始数据里筛选对应的设备id
        const connectionModeType = get(obj, 'properties.spliceClosure.connectionModeType', '')
        // console.log('connectionModeType', connectionModeType)
        // this.$refs.deviceTopo.myNetwork.unselectAll() // 拓扑里，取消所有节点选中
        if (connectionModeType === 'DIRECT_CONNECTION') return
        this.$emit('selectDevice', { ...obj, regionId: this.stationData.nodeId })
        this.spliceClosureHover = false
      },
      hoverNode(obj) {
        // console.log('hoverNode', obj)
        this.spliceClosureHover = false
        if (obj.mouseStatus === 'HOVER') {
          this.spliceClosureHover = true
          this.curNodeData = obj
          // this.hoverPosition = {
          //   left: obj.left + 5 + 'px',
          //   top: obj.top + 5 + 'px'
          // }
        }
        this.$emit('selectDevice', { mouseStatus: 'LEAVE' })
      },
      hoverEdge(obj) {
        if (obj.mouseStatus === 'HOVER') {
          this.activeEdge = obj
          this.hoverPosition = {
            left: obj.left + 5 + 'px',
            top: obj.top + 5 + 'px'
          }
        } else {
          this.activeEdge = { subInfo: {}}
          this.hoverPosition = {
            left: 0,
            top: 0
          }
        }
      },
      close() {
        this.$emit('update:dialogVisible', false)
      }
    }
  }
</script>
<style lang="scss" scoped>
  @import '@/assets/css/mixin.module.scss';
  ::v-deep .device-topo-dialog {
    overflow: hidden;
  }
  .topo-node-box {
    position: relative;
    height: 400px;
    overflow: hidden;
  }
  .topo-node-btn {
    position: absolute;
    right: 0;
    top: 0;
  }
  .el-tabs--card {
    .el-tab-pane {
      width: 180px;
      border-radius: 5px;
      padding: 10px;
      font-size: 12px;
      @include themeify {
        color: themed('gisValueColor');
        background: themed('homeTooltipBg');
        box-shadow: 0px 0px 10px 0px themed('homeTooltipShadow');
      }
      .title {
        @include themeify {
          border-bottom: 1px solid themed('gisTitleColor');
        }
      }
      .item-name {
        @include themeify {
          color: themed('gisTitleColor');
        }
      }
      .item-value {
        @include themeify {
          color: themed('gisValueColor');
        }
      }
    }
  }
</style>
